﻿using Microsoft.Practices.Unity;
using HMIS.FrameWork.Cache;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;
using System.Web;

namespace HMIS.MVC.CommonSupport
{
	public static class ContainerFactory
	{
		public static IUnityContainer GetContainer()
		{

			if (HttpContext.Current.Application["container"] == null)
			{
				IUnityContainer Container = new UnityContainer();
				Container.RegisterType<ICache, WebCache>();//注册缓存

				// 基础数据维护的依赖注入配置
				LoadUnityConfigFile(Container, HttpContext.Current.Server.MapPath("~/unity.di.infrastructure.config"));
				// FSBS的依赖注入配置
				LoadUnityConfigFile(Container, HttpContext.Current.Server.MapPath("~/unity.di.fsbs.config"));


				// 基础数据维护的AOP配置
				LoadUnityConfigFile(Container, HttpContext.Current.Server.MapPath("~/unity.aop.infrastructure.config"));

				HttpContext.Current.Application.Add("container", Container);
			}

			return (IUnityContainer)HttpContext.Current.Application["container"];
		}

		private static void LoadUnityConfigFile(IUnityContainer container, string exeConfigFilename)
		{
			ExeConfigurationFileMap infraFileMap = new ExeConfigurationFileMap
			{
				ExeConfigFilename = exeConfigFilename
			};
			UnityConfigurationSection infraConfig = (UnityConfigurationSection)ConfigurationManager
				.OpenMappedExeConfiguration(infraFileMap, ConfigurationUserLevel.None)
				.GetSection("unity");
			if (infraConfig.Containers.Default != null)
			{
				infraConfig.Containers.Default.Configure(container);
			}
		}
	}
}
